import React, { useRef, useState } from 'react';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { ProTable, PageContainer } from '@ant-design/pro-components';
import { Button, Tag, Modal, Image, Card, Row, Col, Descriptions, message, Select, Space } from 'antd';
import { EyeOutlined, CheckOutlined, CloseOutlined, UserOutlined, TrophyOutlined } from '@ant-design/icons';
import { getTrainerCertifications, reviewTrainerCertification, getTrainerCertificationDetail } from '@/services/game-platform/api';
import type { GamePlatform } from '@/services/game-platform/typings';

const { Option } = Select;

const TrainerCertificationList: React.FC = () => {
  const actionRef = useRef<ActionType>(null);
  const [selectedRecord, setSelectedRecord] = useState<GamePlatform.TrainerCertification | null>(null);
  const [reviewModalVisible, setReviewModalVisible] = useState(false);
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [reviewAction, setReviewAction] = useState<'APPROVE' | 'REJECT'>('APPROVE');
  const [rejectReason, setRejectReason] = useState('');
  const [loading, setLoading] = useState(false);

  // 状态颜色映射
  const statusColorMap = {
    'PENDING': 'processing',
    'APPROVED': 'success',
    'REJECTED': 'error',
    'EXPIRED': 'default',
    'NOT_SUBMITTED': 'default',
  } as const;

  // 状态文本映射
  const statusTextMap = {
    'PENDING': '待审核',
    'APPROVED': '已通过',
    'REJECTED': '已拒绝',
    'EXPIRED': '已过期',
    'NOT_SUBMITTED': '未提交',
  } as const;

  // 技能等级映射
  const skillLevelMap = {
    'BEGINNER': '初级',
    'INTERMEDIATE': '中级',
    'ADVANCED': '高级',
    'EXPERT': '专家',
    'MASTER': '大师',
  } as const;

  const columns: ProColumns<GamePlatform.TrainerCertification>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      width: 80,
      search: false,
    },
    {
      title: '用户信息',
      dataIndex: 'username',
      width: 150,
      render: (_, record) => (
        <div>
          <div><UserOutlined /> {record.username}</div>
          <div style={{ fontSize: '12px', color: '#999' }}>
            {record.userNickname || '未设置昵称'}
          </div>
        </div>
      ),
    },
    {
      title: '擅长游戏',
      dataIndex: 'gameSpecialty',
      width: 120,
      search: false,
    },
    {
      title: '技能等级',
      dataIndex: 'skillLevel',
      width: 100,
      search: false,
      render: (_, record) => (
        <Tag color="blue" icon={<TrophyOutlined />}>
          {skillLevelMap[record.skillLevel as keyof typeof skillLevelMap] || record.skillLevel}
        </Tag>
      ),
    },
    {
      title: '基础价格',
      dataIndex: 'basePrice',
      width: 100,
      search: false,
      render: (_, record) => `¥${record.basePrice?.toFixed(2) || '0.00'}`,
    },
    {
      title: '完成订单数',
      dataIndex: 'completedOrders',
      width: 100,
      search: false,
    },
    {
      title: '评分',
      dataIndex: 'rating',
      width: 100,
      search: false,
      render: (_, record) => record.rating ? `${record.rating.toFixed(1)} ⭐` : '-',
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 100,
      render: (_, record) => {
        const status = record.status as keyof typeof statusColorMap;
        return (
          <Tag color={statusColorMap[status] || 'default'}>
            {statusTextMap[status] || status}
          </Tag>
        );
      },
      valueType: 'select',
      valueEnum: {
        PENDING: { text: '待审核', status: 'Processing' },
        APPROVED: { text: '已通过', status: 'Success' },
        REJECTED: { text: '已拒绝', status: 'Error' },
      },
    },
    {
      title: '提交时间',
      dataIndex: 'submittedAt',
      width: 160,
      valueType: 'dateTime',
      search: false,
    },
    {
      title: '审核时间',
      dataIndex: 'reviewedAt',
      width: 160,
      valueType: 'dateTime',
      search: false,
    },
    {
      title: '操作',
      valueType: 'option',
      width: 200,
      fixed: 'right',
      render: (_, record) => [
        <Button
          key="detail"
          type="link"
          size="small"
          icon={<EyeOutlined />}
          onClick={() => handleViewDetail(record)}
        >
          查看详情
        </Button>,
        record.status === 'PENDING' && (
          <Button
            key="approve"
            type="link"
            size="small"
            icon={<CheckOutlined />}
            style={{ color: '#52c41a' }}
            onClick={() => handleReview(record, 'APPROVE')}
          >
            通过
          </Button>
        ),
        record.status === 'PENDING' && (
          <Button
            key="reject"
            type="link"
            size="small"
            icon={<CloseOutlined />}
            style={{ color: '#ff4d4f' }}
            onClick={() => handleReview(record, 'REJECT')}
          >
            拒绝
          </Button>
        ),
      ].filter(Boolean),
    },
  ];

  // 查看详情
  const handleViewDetail = async (record: GamePlatform.TrainerCertification) => {
    try {
      setLoading(true);
      const response = await getTrainerCertificationDetail(record.id);
      if (response.code === 200 && response.data) {
        setSelectedRecord(response.data);
        setDetailModalVisible(true);
      } else {
        message.error(response.message || '获取详情失败');
      }
    } catch (error) {
      message.error('获取详情失败');
    } finally {
      setLoading(false);
    }
  };

  // 审核操作
  const handleReview = (record: GamePlatform.TrainerCertification, action: 'APPROVE' | 'REJECT') => {
    setSelectedRecord(record);
    setReviewAction(action);
    setRejectReason('');
    setReviewModalVisible(true);
  };

  // 确认审核
  const handleConfirmReview = async () => {
    if (!selectedRecord) return;
    
    if (reviewAction === 'REJECT' && !rejectReason.trim()) {
      message.error('请填写拒绝原因');
      return;
    }

    try {
      setLoading(true);
      const response = await reviewTrainerCertification(selectedRecord.id, {
        action: reviewAction,
        rejectReason: reviewAction === 'REJECT' ? rejectReason : undefined,
      });
      
      if (response.code === 200) {
        message.success(response.message || '审核成功');
        setReviewModalVisible(false);
        actionRef.current?.reload();
      } else {
        message.error(response.message || '审核失败');
      }
    } catch (error) {
      message.error('审核失败');
    } finally {
      setLoading(false);
    }
  };

  return (
    <PageContainer
      title="代练师认证审核"
      subTitle="管理代练师认证申请"
    >
      <ProTable<GamePlatform.TrainerCertification>
        headerTitle="认证申请列表"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            key="refresh"
            onClick={() => actionRef.current?.reload()}
          >
            刷新
          </Button>,
        ]}
        request={async (params) => {
          try {
            const response = await getTrainerCertifications({
              page: (params.current || 1) - 1,
              size: params.pageSize || 20,
              status: params.status as any,
              keyword: params.username,
            });
            
            if (response.code === 200) {
              const data = Array.isArray(response.data) ? response.data : [];
              return {
                data: data,
                success: true,
                total: data.length,
              };
            }
            return {
              data: [],
              success: false,
              total: 0,
            };
          } catch (error) {
            return {
              data: [],
              success: false,
              total: 0,
            };
          }
        }}
        columns={columns}
        scroll={{ x: 1400 }}
        pagination={{
          defaultPageSize: 20,
          showSizeChanger: true,
        }}
      />

      {/* 详情模态框 */}
      <Modal
        title="代练师认证详情"
        open={detailModalVisible}
        onCancel={() => setDetailModalVisible(false)}
        footer={[
          <Button key="close" onClick={() => setDetailModalVisible(false)}>
            关闭
          </Button>,
          selectedRecord?.status === 'PENDING' && (
            <Button
              key="approve"
              type="primary"
              icon={<CheckOutlined />}
              onClick={() => {
                setDetailModalVisible(false);
                handleReview(selectedRecord, 'APPROVE');
              }}
            >
              通过审核
            </Button>
          ),
          selectedRecord?.status === 'PENDING' && (
            <Button
              key="reject"
              danger
              icon={<CloseOutlined />}
              onClick={() => {
                setDetailModalVisible(false);
                handleReview(selectedRecord, 'REJECT');
              }}
            >
              拒绝审核
            </Button>
          ),
        ].filter(Boolean)}
        width={900}
      >
        {selectedRecord && (
          <div>
            <Descriptions title="基本信息" column={2} bordered>
              <Descriptions.Item label="用户名">{selectedRecord.username}</Descriptions.Item>
              <Descriptions.Item label="用户昵称">{selectedRecord.userNickname || '未设置'}</Descriptions.Item>
              <Descriptions.Item label="擅长游戏">{selectedRecord.gameSpecialty}</Descriptions.Item>
              <Descriptions.Item label="技能等级">
                <Tag color="blue" icon={<TrophyOutlined />}>
                  {skillLevelMap[selectedRecord.skillLevel as keyof typeof skillLevelMap] || selectedRecord.skillLevel}
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="基础价格">¥{selectedRecord.basePrice?.toFixed(2) || '0.00'}</Descriptions.Item>
              {selectedRecord.hourlyRate && (
                <Descriptions.Item label="时薪">¥{selectedRecord.hourlyRate.toFixed(2)}/小时</Descriptions.Item>
              )}
              <Descriptions.Item label="每周可用时长">
                {(() => {
                  let hours = 0;
                  if (selectedRecord.availableHours) {
                    if (typeof selectedRecord.availableHours === 'number') {
                      hours = selectedRecord.availableHours;
                    } else if (typeof selectedRecord.availableHours === 'string') {
                      try {
                        const parsed = JSON.parse(selectedRecord.availableHours);
                        hours = Array.isArray(parsed) ? parsed.reduce((sum, h) => sum + h, 0) : 0;
                      } catch {
                        hours = 0;
                      }
                    }
                  }
                  return `${hours} 小时`;
                })()}
              </Descriptions.Item>
              <Descriptions.Item label="当前状态">
                {selectedRecord.isAvailable ? <Tag color="success">在线</Tag> : <Tag color="default">离线</Tag>}
              </Descriptions.Item>
              <Descriptions.Item label="完成订单数">{selectedRecord.completedOrders || 0}</Descriptions.Item>
              <Descriptions.Item label="评分">{selectedRecord.rating ? `${selectedRecord.rating.toFixed(1)} ⭐` : '-'}</Descriptions.Item>
              <Descriptions.Item label="状态">
                <Tag color={statusColorMap[selectedRecord.status as keyof typeof statusColorMap]}>
                  {statusTextMap[selectedRecord.status as keyof typeof statusTextMap]}
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="提交时间">{selectedRecord.submittedAt}</Descriptions.Item>
              {selectedRecord.reviewedAt && (
                <Descriptions.Item label="审核时间">{selectedRecord.reviewedAt}</Descriptions.Item>
              )}
              {selectedRecord.reviewedBy && (
                <Descriptions.Item label="审核人">{selectedRecord.reviewedBy}</Descriptions.Item>
              )}
              {selectedRecord.rejectReason && (
                <Descriptions.Item label="拒绝原因" span={2}>
                  <span style={{ color: 'red' }}>{selectedRecord.rejectReason}</span>
                </Descriptions.Item>
              )}
            </Descriptions>

            {/* 游戏账号信息 */}
            {selectedRecord.gameAccounts && (
              <Card title="游戏账号信息" style={{ marginTop: 16 }} size="small">
                {(() => {
                  let accounts: string[] = [];
                  if (typeof selectedRecord.gameAccounts === 'string') {
                    try {
                      accounts = JSON.parse(selectedRecord.gameAccounts);
                    } catch {
                      accounts = [selectedRecord.gameAccounts];
                    }
                  } else if (Array.isArray(selectedRecord.gameAccounts)) {
                    accounts = selectedRecord.gameAccounts;
                  }
                  return (
                    <ul style={{ margin: 0, paddingLeft: 20 }}>
                      {accounts.map((account, index) => (
                        <li key={index}>{account}</li>
                      ))}
                    </ul>
                  );
                })()}
              </Card>
            )}

            {/* 经验描述 */}
            {selectedRecord.experienceDescription && (
              <Card title="经验描述" style={{ marginTop: 16 }} size="small">
                <div style={{ whiteSpace: 'pre-wrap', wordWrap: 'break-word' }}>
                  {selectedRecord.experienceDescription}
                </div>
              </Card>
            )}

            {/* 技能证明图片/视频 */}
            {(() => {
              // 处理 skillProofUrls 可能是字符串的情况
              let proofUrls: string[] = [];
              if (selectedRecord.skillProofUrls) {
                if (Array.isArray(selectedRecord.skillProofUrls)) {
                  proofUrls = selectedRecord.skillProofUrls;
                } else if (typeof selectedRecord.skillProofUrls === 'string') {
                  try {
                    // 尝试解析 JSON 字符串
                    proofUrls = JSON.parse(selectedRecord.skillProofUrls);
                  } catch {
                    // 如果不是 JSON，尝试逗号分隔
                    proofUrls = selectedRecord.skillProofUrls.split(',').map(url => url.trim()).filter(url => url);
                  }
                }
              }
              
              return proofUrls.length > 0 ? (
                <Card title="技能证明材料" style={{ marginTop: 16 }} size="small">
                  <Row gutter={[16, 16]}>
                    {proofUrls.map((url: string, index: number) => (
                      <Col key={index} span={6}>
                        <div style={{ textAlign: 'center' }}>
                          <div style={{ marginBottom: 8 }}>证明材料 {index + 1}</div>
                          {url.match(/\.(jpg|jpeg|png|gif|webp)$/i) ? (
                            <Image
                              width="100%"
                              src={url}
                              placeholder={
                                <div style={{ height: 150, background: '#f0f0f0', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                                  加载中...
                                </div>
                              }
                            />
                          ) : (
                            <a href={url} target="_blank" rel="noopener noreferrer">
                              <div style={{ height: 150, background: '#f0f0f0', display: 'flex', alignItems: 'center', justifyContent: 'center', border: '1px dashed #d9d9d9' }}>
                                点击查看视频
                              </div>
                            </a>
                          )}
                        </div>
                      </Col>
                    ))}
                  </Row>
                </Card>
              ) : null;
            })()}

            {/* 备注信息 */}
            {selectedRecord.notes && (
              <Card title="备注信息" style={{ marginTop: 16 }} size="small">
                <div style={{ whiteSpace: 'pre-wrap', wordWrap: 'break-word' }}>
                  {selectedRecord.notes}
                </div>
              </Card>
            )}
          </div>
        )}
      </Modal>

      {/* 审核模态框 */}
      <Modal
        title={`${reviewAction === 'APPROVE' ? '通过' : '拒绝'}审核`}
        open={reviewModalVisible}
        onCancel={() => setReviewModalVisible(false)}
        onOk={handleConfirmReview}
        confirmLoading={loading}
      >
        {selectedRecord && (
          <div>
            <p>
              确定要{reviewAction === 'APPROVE' ? '通过' : '拒绝'}用户 <strong>{selectedRecord.username}</strong> 的代练师认证申请吗？
            </p>
            <Space direction="vertical" style={{ width: '100%' }}>
              <div>
                <strong>擅长游戏：</strong>{selectedRecord.gameSpecialty}
              </div>
              <div>
                <strong>技能等级：</strong>
                {skillLevelMap[selectedRecord.skillLevel as keyof typeof skillLevelMap] || selectedRecord.skillLevel}
              </div>
              <div>
                <strong>基础价格：</strong>¥{selectedRecord.basePrice?.toFixed(2) || '0.00'}
              </div>
            </Space>
            {reviewAction === 'REJECT' && (
              <div style={{ marginTop: 16 }}>
                <label>拒绝原因：</label>
                <Select
                  style={{ width: '100%', marginTop: 8 }}
                  placeholder="请选择拒绝原因"
                  value={rejectReason}
                  onChange={setRejectReason}
                  allowClear
                >
                  <Option value="技能证明材料不充分">技能证明材料不充分</Option>
                  <Option value="游戏水平未达到要求">游戏水平未达到要求</Option>
                  <Option value="经验描述不详细">经验描述不详细</Option>
                  <Option value="提交的信息不真实">提交的信息不真实</Option>
                  <Option value="游戏账号信息有误">游戏账号信息有误</Option>
                  <Option value="不符合平台代练师标准">不符合平台代练师标准</Option>
                  <Option value="其他原因">其他原因</Option>
                </Select>
              </div>
            )}
          </div>
        )}
      </Modal>
    </PageContainer>
  );
};

export default TrainerCertificationList;

